﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Xml;
using System.Reflection;

namespace Pop3Client
{
    class MailParser
    {
        public List<object> ParseMail(MailMessage mail)
        {
            return ParseMail(mail.Body);
        }

        public List<object> ParseMail(string mail)
        {
            List<object> objects = new List<object>();
            if (!String.IsNullOrWhiteSpace(mail))
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(mail);
                foreach (XmlNode typeNode in doc.SelectSingleNode("Datensatz").ChildNodes)
                {
                    Type t = Type.GetType("Pop3Client." + typeNode.Attributes["dbName"].Value);
                    object o = Activator.CreateInstance(t);
                    foreach (XmlNode node in typeNode.ChildNodes)
                    {
                        PropertyInfo pi = t.GetProperty(node.Name);
                        if (pi != null)
                        {
                            if (!String.IsNullOrWhiteSpace(node.InnerText))
                            {
                                object value = pi.GetType().GetMethod("Parse").Invoke(null, new object[] { node.InnerText });
                                pi.SetValue(o, value, null);
                            }
                        }
                    }
                    objects.Add(o);
                }
            }
            return objects;
        }
    }
}
